package com.shajj.movie.subtitle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;
import com.shajj.movie.DataManager;
import com.shajj.movie.PMF;
import com.shajj.movie.Subtitle;
import com.shajj.movie.SerializableList;

public class SubtitleDataManager implements DataManager<Subtitle> {
	private PersistenceManager persistenceManager;
	private Query singleQuery;
	private Query pageQuery;

	private Cache cache;

	private static SubtitleDataManager instance = new SubtitleDataManager();

	public static SubtitleDataManager getInstance() {
		return instance;
	}

	public SubtitleDataManager() {
		persistenceManager = PMF.get().getPersistenceManager();
		singleQuery = persistenceManager.newQuery(Subtitle.class, "id == idParam");
		singleQuery.declareParameters("Long idParam");
		pageQuery = persistenceManager.newQuery(Subtitle.class);
		try {
			Map<Integer, Integer> props = new HashMap<Integer, Integer>();
			props.put(GCacheFactory.EXPIRATION_DELTA, 5 * 60);
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(props);
		} catch (CacheException e) {
		}
	}

	@SuppressWarnings("unchecked")
	public Subtitle get(Long id) {
		List<Subtitle> list = (List<Subtitle>) singleQuery.execute(id);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Subtitle> getByCache(int start, int size) {
		String key = String.valueOf(start) + "_" + String.valueOf(size);
		Object records = cache.get("key");
		if (records == null) {
			records = getByPage(start, size);
			cache.put(key, records);
		}
		return (List<Subtitle>) records;
	}

	@SuppressWarnings("unchecked")
	public List<Subtitle> getByPage(int start, int size) {
		pageQuery.setRange(start, start + size);
		pageQuery.setOrdering("time desc");
		return new SerializableList<Subtitle>((List<Subtitle>) pageQuery.execute());
	}

	@Override
	public void save(Subtitle record) {
		persistenceManager.makePersistent(record);
	}

	@Override
	public List<Subtitle> search(String queryString) {
		return SubtitleSearchJanitor.search(queryString, persistenceManager);
	}
}
